package net.lab1024.sa.ai.stream.module.business.ai.controller;

import net.lab1024.sa.ai.stream.module.business.ai.model.dto.AiChatRequestDTO;
import net.lab1024.sa.ai.stream.module.business.ai.service.AiModelInvokeService;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;

@RestController
@RequestMapping("/api/ai/invoke")
public class AiModelInvokeController {

    private static final Logger log = LoggerFactory.getLogger(AiModelInvokeController.class);

    @Autowired
    private AiModelInvokeService aiModelInvokeService;

    @PostMapping("/chat")
    public ResponseDTO<String> chat(@RequestBody AiChatRequestDTO request) {
        String result = aiModelInvokeService.chat(request);
        return ResponseDTO.ok(result);
    }

    @PostMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> chatStream(@RequestBody AiChatRequestDTO request, ServerHttpResponse response) {
        response.getHeaders().setContentType(MediaType.TEXT_EVENT_STREAM);
        response.getHeaders().add("Cache-Control", "no-cache");
        response.getHeaders().add("Connection", "keep-alive");
        response.getHeaders().add("X-Debug", "stream");
        log.info("[Controller] chatStream called, modelName: {}, roleId: {}", request.getModelName(), request.getRoleId());
        return aiModelInvokeService.chatStream(request);
    }
}